import { lang } from '@common/entry';
import Cookies from 'js-cookie';
import basic from '@common/basic';
const { getUUid } = basic.getExportResource('@/basic/business-modules/dash-board/config/index.js');
import Sortable from 'sortablejs';
import { cloneDeep } from 'lodash';
export const managementEnumTable = (emit, props) => {
  const { t } = lang.global;
  const { commandFunc } = inject('apiFunTools');
  const tyPlmEditGridLogin = ref(false);
  const tableColumns = ref([]);
  const insertToTopNum = ref(1);
  const insertToBottomNum = ref(1);
  const baseTableRef = ref(null);
  const sortable1 = ref(null);
  const isChineseShow = ref(false);
  const metaData = ref([]); // 表格的原始数据
  const gridOptions = ref({
    showHeader: true,
    showHeaderOverflow: true,
    showOverflow: true,
    height: 'auto',
    autoResize: true,
    rowId: 'oid',
    columnConfig: {
      resizable: true
    },
    scrollY: {
      enabled: true,
      gt: 10
    },
    // modify by cuiwb 2025/3/20 枚举管理ucd样式修改
    rowConfig: {
      height: 32,
      isCurrent: true,
      isHover: true,
      useKey: true
    },
    editConfig: {
      trigger: 'click',
      mode: 'cell',
      autoClear: true,
      beforeEditMethod: ({ row }) => {
        return row.iconStatus != 'delet';
      }
    },
    data: [],
    columns: [],
    appendCellClassName: (row, field) => {
      let arr = ['dragIcon', 'checkbox', 'statusIcon', 'serial'];
      if (row.iconStatus == 'delet' && arr.indexOf(field) == -1) {
        return ' delet-cell-enum ';
      }
      // modify by cuiwb 2025/3/20 枚举管理ucd样式修改
      return '';
    }
  });
  const rule = ref({
    internalName: [
      { required: true, message: t('message.requiredWith'), trigger: 'blur' },
      { noRepetition: true, message: t('message.repeatInput'), trigger: 'blur' }
    ]
  });
  let gridColumnsChinese = [
    { field: 'dragIcon', fixed: 'left', width: 32 },
    { field: 'checkbox', fixed: 'left', width: 50, type: 'checkbox', align: 'center' },
    { field: 'serial', title: t('basic.label.order'), fixed: 'left', width: 60, align: 'center' },
    // 内部名称
    {
      field: 'internalName',
      title: t('basic.label.internalName'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 显示名称
    {
      field: 'displayName',
      title: t('basic.table.displayname'),
      editRender: { autofocus: '.el-input__inner' }
    },
    // 说明
    {
      field: 'description',
      title: t('basic.label.explanation'),
      editRender: { autofocus: '.el-input__inner' }
    },
    // 色卡
    { field: 'colorchart', title: t('basic.label.colorCard') },
    // 启用
    {
      field: 'state',
      title: t('basic.label.start')
    }
  ];
  let gridColumns = [
    { field: 'dragIcon', fixed: 'left', width: 32 },
    { field: 'checkbox', fixed: 'left', width: 50, type: 'checkbox' },
    // modify by cuiwb 2025/3/20 枚举管理ucd样式修改
    { field: 'serial', title: t('basic.label.order'), fixed: 'left', width: 60, align: 'center' },
    // 内部名称
    {
      field: 'internalName',
      title: t('basic.label.internalName'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 显示名称(中文)
    {
      field: 'displayNameCn',
      title: t('basic.label.displayNameChinese'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 显示名称(英文)
    {
      field: 'displayNameEn',
      title: t('basic.label.displayNameEnglish'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 说明(中文)
    {
      field: 'descriptionCn',
      title: t('basic.label.explanationChinese'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 说明(英文)
    {
      field: 'descriptionEn',
      title: t('basic.label.explanationEnglish'),
      editRender: {
        autofocus: '.el-input__inner'
      }
    },
    // 色卡
    { field: 'colorchart', title: t('basic.label.colorCard') },
    // 启用
    {
      field: 'state',
      title: t('basic.label.start')
    }
  ];
  const isChinese = val => {
    tableColumns.value = val ? gridColumnsChinese : gridColumns;
    gridOptions.value.columns = val ? gridColumnsChinese : gridColumns;
    isChineseShow.value = val;
  };
  //获取列表数据
  function getTableList() {
    const params = { oid: props.currentEnumRow.oid };
    const callback = val => {
      val.forEach(data => {
        data.noAdd = true;
      });
      metaData.value = val;
      handleSearch();
      emit('setBatchEditLoading', false);
      tyPlmEditGridLogin.value = true;
      nextTick(() => {
        if (!sortable1.value) {
          initSortable();
        }
      });
    };
    commandFunc('$backendmrgapis', 'enum-management', 'queryEnumerationItemByDefOid', params, {
      callback,
      exceptionCallback: e => {
        console.info(e);
        emit('setBatchEditLoading', false);
      }
    });
  }
  const currentMouseEnterSerialRow = ref({});
  const cellMouseEnter = val => {
    currentMouseEnterSerialRow.value = val;
  };
  const handleDropdownMenu = ref({
    trigger: 'hover',
    hideOnClick: false,
    isEnum: true,
    showArrowIcon: false,
    placement: 'bottom-start',
    teleported: true,
    popperClass: 'container-craft-opts-popover',
    popperOptions: {
      strategy: 'fixed'
    },
    list: [
      {
        command: 'insertUp',
        icon: 'iconfont font-14 icon-moveup',
        label: t('btn.insertUp'),
        value: '4',
        type: 'inputNum',
        disabled: false
      },
      {
        command: 'insertDown',
        icon: 'iconfont font-14 icon-movedown',
        label: t('btn.insertDown'),
        value: '5',
        type: 'inputNum',
        splitLine: true,
        disabled: false
      },
      {
        command: 'rowDelete',
        icon: 'iconfont font-14 icon-operation-delete',
        label: t('btn.delete'),
        value: '6',
        type: 'text',
        disabled: false
      },
      {
        command: 'rowRecover',
        icon: 'iconfont font-14 icon-huifu1',
        label: t('btn.recover'),
        value: '7',
        type: 'text',
        disabled: false
      }
    ],
    buttonOptions: {
      iconClass: 'iconfont icon-operation-more btn-craft-opts',
      type: 'text',
      loading: false,
      disabled: false
    }
  });
  const colorList1 = ref([
    '#FDE5E4',
    '#FDE4F2',
    '#F6E5F9',
    '#F1EAFF',
    '#EAECFB',
    '#DDECFF',
    '#CCEFFC',
    '#CCF1EC',
    '#D8F2D5',
    '#ECF3CC',
    '#FDF5CC',
    '#F8E9CC',
    '#FEE7CC',
    '#E9EAEC'
  ]);
  const colorList2 = ref([
    '#F75550',
    '#EF57AD',
    '#DE59DE',
    '#A571FE',
    '#7C84EE',
    '#5789FE',
    '#0B9BD3',
    '#02A28C',
    '#1BA70C',
    '#95B200',
    '#DBC500',
    '#B28900',
    '#DB7500',
    '#646A73'
  ]);
  const colorList = ref([...colorList1.value, ...colorList2.value]);
  const colorListNum = ref(0);
  /**
   * @description 行操作
   */
  const handleToOptionsRow = (val, row) => {
    const insertObj = setArr(insertToTopNum.value);
    const metaTarget = metaData.value.find(item => item.oid == row.oid) || {};
    switch (val) {
      // 向上插入
      case '4':
        gridOptions.value.data.splice(baseTableRef.value.tyPlmGridRef.grid.getRowIndex(row), 0, ...insertObj);
        metaData.value.splice(baseTableRef.value.tyPlmGridRef.grid.getRowIndex(row), 0, ...insertObj);
        break;
      // 向下插入
      case '5':
        gridOptions.value.data.splice(baseTableRef.value.tyPlmGridRef.grid.getRowIndex(row) + 1, 0, ...insertObj);
        metaData.value.splice(baseTableRef.value.tyPlmGridRef.grid.getRowIndex(row) + 1, 0, ...insertObj);
        break;
      // 删除
      case '6':
        if (row.isAddStatus) {
          gridOptions.value.data.splice(gridOptions.value.data.indexOf(row), 1);
          metaData.value.splice(metaData.value.indexOf(row), 1);
        } else {
          row.iconStatus = 'delet';
          // modify by weig 2025/6/4 Fix:Bug# 28333 【SIT-PG】删除枚举提示修改成功，实际未删除
          metaTarget.iconStatus = 'delet';
        }
        break;
      // 恢复
      case '7':
        row.iconStatus = 'edit';
        metaTarget.iconStatus = 'edit';
        break;
      default:
        break;
    }
    insertToTopNum.value = 1;
    insertToBottomNum.value = 1;
  };
  const getRowIndex = val => {
    return baseTableRef.value.tyPlmGridRef.grid.getRowIndex(val) + 1;
  };
  const setArr = val => {
    let arr = [];
    for (let i = 0; i < val; i++) {
      arr.push({
        iconStatus: 'add',
        state: 'true',
        oid: getUUid(),
        repeat: true,
        internalNameMsgTips: true,
        flagAdd: true,
        isAddStatus: true,
        colorchart: colorList.value[colorListNum.value]
      });
      colorListNum.value++;
      if (colorListNum.value == colorList.value.length - 1) colorListNum.value = 0;
    }
    return arr;
  };
  const handleStatusIcon = row => {
    let iconClass = '';
    switch (row.iconStatus) {
      case 'add':
        iconClass = 'iconfont font-14 icon-xinjian2';
        break;
      case 'edit':
        iconClass = 'iconfont font-14 icon-operation-edit1';
        break;
      case 'delet':
        iconClass = 'iconfont font-14 icon-operation-delete';
        break;
      default:
        iconClass = 'iconfont font-14 icon-operation-edit1';
        break;
    }
    return iconClass;
  };
  const initSortable = () => {
    nextTick(() => {
      const xTable = baseTableRef.value.tyPlmGridRef.grid;
      sortable1.value = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
        handle: '.drag-handler-craft',
        animation: 200,
        onEnd: ({ newIndex, oldIndex }) => {
          const toRow = cloneDeep(gridOptions.value.data)[newIndex]; // 要拖入的行对象
          const currRow = cloneDeep(gridOptions.value.data)[oldIndex]; // 当前拖动的行对象
          const fromIndex = metaData.value.findIndex(item => item.oid == currRow.oid);
          const toIndex = metaData.value.findIndex(item => item.oid == toRow.oid);
          metaData.value.splice(fromIndex, 1);
          metaData.value.splice(toIndex, 0, currRow);
          gridOptions.value.data.splice(oldIndex, 1);
          gridOptions.value.data.splice(newIndex, 0, currRow);

          const list = gridOptions.value.data.slice();
          gridOptions.value.data = [];
          nextTick(() => {
            gridOptions.value.data = list;
          });
        }
      });
    });
  };
  /**
   * @description 批量添加
   */
  function batchToAdd(val) {
    const newData = setArr(val);
    gridOptions.value.data.push(...newData);
    metaData.value.push(...newData);
  }

  //粘贴，插入行
  function handleInsertCopyRow(datas, type) {
    if (!datas.length) return;
    datas.forEach(data => {
      data.iconStatus = 'add';
      data.state = 'true';
      data.oid = getUUid();
      data.internalNameMsgTips = true;
      data.flagAdd = true;
      data.isAddStatus = true;
      data.colorchart = colorList.value[colorListNum.value];
    });
    colorListNum.value++;
    if (colorListNum.value == colorList.value.length - 1) colorListNum.value = 0;
    const clickRowIndex = baseTableRef.value.tyPlmGridRef.grid.getRowIndex(
      baseTableRef.value.tyPlmGridRef.grid.getCurrentRecord()
    );
    if (clickRowIndex == -1) {
      gridOptions.value.data.push(...datas);
      metaData.value.push(...datas);
      baseTableRef.value.validate();
    } else {
      if (type == 'insert') {
        //插入行
        gridOptions.value.data.splice(clickRowIndex + 1, 0, ...datas);
        metaData.value.splice(clickRowIndex + 1, 0, ...datas);
        baseTableRef.value.validate();
      } else {
        //粘贴行
        let datasLength = datas.length;
        let arrlin = gridOptions.value.data.length - clickRowIndex;
        if (arrlin >= datasLength) {
          gridOptions.value.data.splice(clickRowIndex, datasLength, ...datas);
          metaData.value.splice(clickRowIndex, datasLength, ...datas);
          let arr = gridOptions.value.data.slice();
          gridOptions.value.data = [];
          nextTick(() => {
            gridOptions.value.data = arr;
            baseTableRef.value.validate();
          });
        } else {
          gridOptions.value.data.splice(clickRowIndex, arrlin, ...datas);
          metaData.value.splice(clickRowIndex, arrlin, ...datas);
          baseTableRef.value.validate();
        }
      }
    }
  }
  const selectChangeEvent = () => {
    const records = baseTableRef.value.tyPlmGridRef.grid.getCheckboxRecords();
    emit('selectChangeEvent', records);
  };
  const clearEdit = () => {
    console.log('clearEdit');
    baseTableRef.value.tyPlmGridRef.grid.clearEdit();
  };
  const handleDisplayChange = (val, row) => {
    row[`displayName${Cookies.get('syslang') == 'en' ? 'En' : 'Cn'}`] = val;
    row.displayNamemainText = val;
    const target = metaData.value.find(item => item.oid == row.oid);
    target[`displayName${Cookies.get('syslang') == 'en' ? 'En' : 'Cn'}`] = val;
    target.displayNamemainText = val;
  };
  const handleDescriptionChange = (val, row) => {
    row[`description${Cookies.get('syslang') == 'en' ? 'En' : 'Cn'}`] = val;
    row.descriptionmainText = val;
    const target = metaData.value.find(item => item.oid == row.oid);
    target[`description${Cookies.get('syslang') == 'en' ? 'En' : 'Cn'}`] = val;
    target.descriptionmainText = val;
  };
  // modify by cuiwb 2025/3/20 枚举管理ucd样式修改
  const visibleDropdownRowId = ref(null);
  /**
   * @description 设置当前下拉的dropdownRowId
   * @param {*} flag true:显示 false:隐藏
   * @param {*} row 行对象
   * @return {*}
   */
  const handleVisibleChange = (flag, row) => {
    visibleDropdownRowId.value = flag ? row.oid : null;
  };

  /**
   * @description 表格的过滤
   * @param {string} keywords 输入的关键字
   */
  const handleSearch = keywords => {
    if (keywords) {
      const filterData = metaData.value.filter(item => {
        return (
          (item.internalName || '').toLowerCase().includes(keywords.toLowerCase()) ||
          (item.displayNameCn || '').toLowerCase().includes(keywords.toLowerCase()) ||
          (item.displayNameEn || '').toLowerCase().includes(keywords.toLowerCase()) ||
          (item.descriptionCn || '').toLowerCase().includes(keywords.toLowerCase()) ||
          (item.descriptionEn || '').toLowerCase().includes(keywords.toLowerCase())
        );
      });
      gridOptions.value.data = cloneDeep(filterData);
    } else {
      gridOptions.value.data = cloneDeep(metaData.value);
    }
  };

  /**
   * @description 编辑表单的数据修改完之后的处理逻辑
   * @Author weig
   * @Date 2025-05-06 17:34:33
   * @param {*} row
   */
const handleEdit = ({ row }) => {
  const target = metaData.value.find(item => item.oid === row.oid);
  if (!target) return;

  const lang = Cookies.get('syslang');               // 'zh'|'en'
  const field = lang === 'en' ? 'displayNameEn' : 'displayNameCn';
  const raw = (row[field] ?? '').trim();

  const idx = raw.indexOf('___');

  /* 1. 无分隔符：显示名=输入，内部名=直接刷时间戳 */
  if (idx === -1) {
    target[field] = row[field] = raw;                // 显示名称保持输入
    const code = Date.now().toString();              // 毫秒时间戳
    target.internalName = row.internalName = code;   // 内部名称强制刷新
    return;
  }

  /* 2. 有分隔符：老逻辑 */
  const left = raw.slice(0, idx).trim();
  const right = raw.slice(idx + 3).trim();

  const newInternal = left || Date.now().toString(); // 空就用时间戳
  target.internalName = row.internalName = newInternal;
  target[field] = row[field] = right;
};

  /**
   * @description 修改显示值的回调
   * @Author weig
   * @Date 2025-05-06 18:18:38
   * @param {*} list
   * @param {*} row 行数据
   * @param {*} mainText 主文本的值
   */
  const displayNameConfirm = (mainText, list, row) => {
    row.displayNamemainText = mainText;
    row.displayNameCn = list[0].value;
    row.displayNameEn = list[1].value;
    let target = metaData.value.find(item => item.oid == row.oid);
    if (target) {
      target.displayNamemainText = mainText;
      target.displayNameCn = list[0].value;
      target.displayNameEn = list[1].value;
    }
  };

  /**
   * @description 修改描述的回调
   * @Author weig
   * @Date 2025-05-06 18:18:38
   * @param {*} list
   * @param {*} row 行数据
   * @param {*} mainText 主文本的值
   */
  const descriptionConfirm = (mainText, list, row) => {
    row.descriptionmainText = mainText;
    row.descriptionCn = list[0].value;
    row.descriptionEn = list[1].value;
    let target = metaData.value.find(item => item.oid == row.oid);
    if (target) {
      target.descriptionmainText = mainText;
      target.descriptionCn = list[0].value;
      target.descriptionEn = list[1].value;
    }
  };

  /**
   * @description 色卡选中的回调
   * @Author weig
   * @Date 2025-05-06 18:18:38
   * @param {*} row 行数据
   * @param {*} color 颜色值
   */
  const handleChooseColor = (row, color) => {
    row.colorchart = color;
    let target = metaData.value.find(item => item.oid == row.oid);
    if (target) {
      target.colorchart = color;
    }
  };
  /**
   * @description 启停用的回调
   * @Author weig
   * @Date 2025-05-06 18:18:38
   * @param {*} row 行数据
   * @param {*} val 开启还是关闭
   */
  const stateChange = (row, val) => {
    let target = metaData.value.find(item => item.oid == row.oid);
    if (target) {
      target.state = val;
    }
  };

  const internalNameChange = row => {
    const target = metaData.value.find(item => item.oid == row.oid);
    if (target) {
      target.internalName = row.internalName;
    }
  };
  onMounted(() => {
    if (props.currentEnumRow.iscolored == 0) {
      // modify by weig 2025/5/7 当枚举不支持色卡的时候枚举管理色卡这一列不显示
      gridColumns = gridColumns.filter(item => item.field != 'colorchart');
      gridColumnsChinese = gridColumnsChinese.filter(item => item.field != 'colorchart');
      tableColumns.value = gridColumns;
    }
    isChinese(false);
    getTableList();
  });
  return {
    gridOptions,
    rule,
    isChinese,
    tableColumns,
    tyPlmEditGridLogin,
    cellMouseEnter,
    currentMouseEnterSerialRow,
    handleToOptionsRow,
    handleDropdownMenu,
    insertToTopNum,
    insertToBottomNum,
    getRowIndex,
    baseTableRef,
    getTableList,
    handleStatusIcon,
    batchToAdd,
    handleInsertCopyRow,
    selectChangeEvent,
    clearEdit,
    isChineseShow,
    handleDisplayChange,
    handleDescriptionChange,
    visibleDropdownRowId,
    handleVisibleChange,
    handleSearch,
    metaData,
    internalNameChange,
    handleEdit,
    displayNameConfirm,
    descriptionConfirm,
    handleChooseColor,
    stateChange
  };
};
